package com.uranus.auth.auth.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.uranus.auth.auth.beans.Captcha;
import com.uranus.auth.auth.beans.SmsProperties;
import com.uranus.auth.auth.mapper.CaptchaMapper;
import com.uranus.auth.auth.request.captcha.SendCaptchaRequest;
import com.uranus.auth.auth.service.CaptchaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uranus.common.VO.Result;
import com.uranus.common.bean.expection.BusinessException;
import com.uranus.common.constant.enums.LoginTypeEnum;
import com.uranus.common.util.DateUtils;
import com.uranus.common.util.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * <p>
 *  验证码服务 手机和邮箱
 * </p>
 * @author ybx
 * @since 2018-12-24
 */
@Service
public class CaptchaServiceImpl extends ServiceImpl<CaptchaMapper, Captcha> implements CaptchaService {

    @Autowired
    private SmsProperties smsProperties;

    @Value("${custom.emailProperties.sendFlag}")
    private Boolean EmailSendFlag;

    @Autowired
    private JavaMailSender mailSender ;
    private IAcsClient acsClient;
    private static final String region = "cn-hangzhou";
    @PostConstruct
    public void init() throws ClientException {
        System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(smsProperties.getDefaultConnectTimeout()));
        System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(smsProperties.getDefaultReadTimeout()));
        IClientProfile profile = DefaultProfile.getProfile(region, smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
        DefaultProfile.addEndpoint(region, region, "Dysmsapi", "dysmsapi.aliyuncs.com");
        acsClient = new DefaultAcsClient(profile);
    }

    /**
     * 创建验证码
     */
    @Override
    public Result createCaptcha(SendCaptchaRequest req) {
        if(req.getCaptchaType()==null || req.getCaptchaType()==0){
            req.setCaptchaType(1);
        }
        QueryWrapper<Captcha> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver",req.getReceiver()).eq("captcha_type",req.getCaptchaType());
        Captcha captcha=this.baseMapper.selectOne(queryWrapper);
        if(captcha==null){
            captcha=new Captcha();
            captcha.setCreateTime(new Date());
        }
        captcha.setCaptchaType(req.getCaptchaType());
        captcha.setUpdateTime(new Date());
        captcha.setReceiver(req.getReceiver());
        if(req.getSenderType()== LoginTypeEnum.mobile){
            return createMobileCaptcha(req,captcha);
        }else{
            return createEmailCaptcha(req,captcha);
        }
    }
    /**
     *创建短信验证码
     */

    private Result createMobileCaptcha(SendCaptchaRequest req, Captcha captcha){
        captcha.setCaptcha("666666");
        if(smsProperties.isSendFlag()){
            captcha.setCaptcha(Encrypt.getRandomNumber(6));
        }
        this.saveOrUpdate(captcha);

        if(smsProperties.isSendFlag()){

        }
        return Result.buildSuccess();
    }
    /**
     *创建邮箱验证码
     */
    private Result createEmailCaptcha(SendCaptchaRequest req ,Captcha captcha){
        captcha.setCaptcha("666666");
        if(EmailSendFlag){
            captcha.setCaptcha(Encrypt.getRandomNumber(6));
        }
        this.saveOrUpdate(captcha);
        if(EmailSendFlag){
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("m13716252314@163.com");
            String [] receiver={captcha.getReceiver(),"m13716252314@163.com"};
            message.setTo(receiver);
            message.setSubject("Uranus的验证通知");
            message.setText(String.format("亲爱的会员，%s 是您本次的验证码，1分钟内有效,请勿泄露给其他人！",captcha.getCaptcha()));
            try {
                mailSender.send(message);
                return Result.buildSuccess();
            } catch (Exception e) {
                throw  new BusinessException("邮件验证发送失败");
            }
        }


        return Result.buildSuccess();
    }


    @Override
    public boolean checkCaptcha(SendCaptchaRequest req, String captcha) {
        if(req.getCaptchaType()==null || req.getCaptchaType()==0){
            req.setCaptchaType(1);
        }
        QueryWrapper<Captcha> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receiver",req.getReceiver()).eq("captcha_type",req.getCaptchaType());
        Captcha captchaEntity=this.baseMapper.selectOne(queryWrapper);
        if(captchaEntity==null || !captchaEntity.getCaptcha().equals(captcha)){
            throw new BusinessException("输入的验证码不正确，请重新输入");
        }
        if(DateUtils.getDateDiff(captchaEntity.getUpdateTime(),new Date())>300){
            throw new BusinessException("验证码失效，请重新获取验证码");
        }
        return true;
    }



}
